
package com.pay.yifutong.util;


import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;


public class SignUtil {

	public static String signData(Map<String, String> Map, String privateKeyFile) throws Exception {
		Map<String, String> tMap = new TreeMap<String, String>();
		for (Entry<String, String> entry : Map.entrySet()) {
			if (StringUtils.isNotBlank(entry.getValue())) {
				tMap.put(entry.getKey(), entry.getValue());
			}
		}
		StringBuffer buf = new StringBuffer();
		for (String key : tMap.keySet()) {
			buf.append(key).append("=").append((String) tMap.get(key)).append("&");
		}
		String signatureStr = buf.substring(0, buf.length() - 1);
		String signData = RSACoder.signMSByPrivateKeyFile(signatureStr, privateKeyFile);
		return signData;
	}

	public static boolean verferSignData(Map<String, String> Map, String publicKeyFile) throws Exception {
		if (Map != null && Map.size() > 0) {
			StringBuffer buf = new StringBuffer();
			String signature = "";
			for (String key : Map.keySet()) {
				if ("signature".equals(key)) {
					signature = Map.get(key).replace(" ", "+");
				} else if(StringUtils.isNotBlank(Map.get(key))){
					buf.append(key).append("=").append((String) Map.get(key)).append("&");
				}else{
					//continue
				}
			}
			String signatureStr = buf.substring(0, buf.length() - 1);
			return RSACoder.verifyMSByPublicKeyFile(signatureStr, signature, publicKeyFile);
		}
		return false;
	}
}
